package com.example.controller;


import com.example.common.BaseResponse;
import com.example.common.ErrorCode;
import com.example.common.ResultUtils;
import com.example.exception.BusinessException;
import com.example.model.user.*;
import com.example.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.example.contant.UserConstant.*;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户登录
     *
     * @param userLoginRequest 用户登录实体
     * @param request          HttpServletRequest
     * @return 脱敏后用户信息
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        log.info(userLoginRequest.toString());
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        String userName = userLoginRequest.getUsername();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userName, userPassword)) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User user = userService.userLogin(userName, userPassword, request);
        System.out.println(user.toString());
        return ResultUtils.success(user);
    }

    /**
     * 用户注册
     * @param userRegisterRequest 注册实体
     * @return 1
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest){
        if (userRegisterRequest==null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        String userName=userRegisterRequest.getUsername();
        String userPassword=userRegisterRequest.getUserPassword();
        String checkPassword=userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userName, userPassword,checkPassword)) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        Long id=userService.userRegister(userName,userPassword,checkPassword);
        return ResultUtils.success(id);
    }

    /**
     * 获取用户登录态
     *
     * @param request HttpServletRequest
     * @return 登录用户信息
     */
    @GetMapping("/current")
    public BaseResponse<User> current(HttpServletRequest request){
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        if (user == null) {
            return null;
        }
        user = userService.getById(user.getId());
        return ResultUtils.success(user);
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "request==null");
        }
        Integer i = userService.userLogout(request);
        return ResultUtils.success(i);
    }

    /**
     * 获取用户集合
     * @param username 用户名模糊查询
     * @param request HttpServletRequest
     * @return 用户集合
     */
    @GetMapping("/search")
    public BaseResponse<List<User>> getUserList(String username,HttpServletRequest request) {
        if (!isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH,"权限不足");
        }
        List<User> userList;
        if (username == null) {
            userList=userService.getUserList();
        }else
            userList=userService.getUserByName(username);
        return ResultUtils.success(userList);
    }

    /**
     * 更新用户
     * @param userUpdateRequest 更新用户实体
     * @param request HttpServletRequest
     * @return 是否成功
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest, HttpServletRequest request) {
        if (!isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH,"权限不足");
        }
        Boolean result=userService.updateUser(userUpdateRequest);
        return ResultUtils.success(result);
    }

    /**
     * 编辑个人信息
     * @param personalInfo 个人信息
     * @return 是否成功
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> updateInfo(@RequestBody EditPersonalInfo personalInfo){
        if (personalInfo==null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        Boolean result=userService.updateInfo(personalInfo);
        return ResultUtils.success(result);
    }

    /**
     * 修改密码
     * @return 是否修改成功
     */
    @PostMapping("/password")
    public BaseResponse<Boolean> updatePassword(@RequestBody UpdatePassword updatePassword){
        if (updatePassword==null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        Boolean result=userService.updatePassword(updatePassword);
        return ResultUtils.success(result);
    }

    /**
     * 删除用户
     * @param id 用户id
     * @param request HttpServletRequest
     * @return 是否删除成功
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(Long id, HttpServletRequest request) {
        if (!isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH,"权限不足");
        }
        Boolean result=userService.deleteUser(id);
        if (!result)
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"删除失败");
        return ResultUtils.success(true);
    }

    /**
     *  重置密码
     * @param id 用户id
     * @param request HttpServletRequest
     * @return 是否成功
     */
    @GetMapping("/resetUser")
    public BaseResponse<Boolean> resetPassword(Long id,HttpServletRequest request) {
        if (!isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        Boolean result=userService.resetPassword(id);
        return ResultUtils.success(result);
    }

    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    private boolean isAdmin(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
//        if (user == null || (user.getUserRole() != ADMIN_ROLE && user.getUserRole() != SUPER_ADMIN_ROLE))
//            return false;
//        return true;
        if (userObj == null || !(userObj instanceof User)) {
            // userObj 是 null 或者不是 User 类型，返回 false
            return false;
        }
        // 检查用户角色是否为 1 或 2
        return user.getUserRole() == ADMIN_ROLE || user.getUserRole() == SUPER_ADMIN_ROLE;
    }
}
